package com.dzb.langchain4j.common.config;

import com.dzb.langchain4j.store.MongoChatMemoryStore;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.elasticsearch.ElasticsearchConfigurationKnn;
import dev.langchain4j.store.embedding.elasticsearch.ElasticsearchEmbeddingStore;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: dzbiao
 * @CreateTime: 2025/06/08 12:13
 * @Description:
 */
@Configuration
public class XiaozhiAgentConfig {
    @Autowired
    private MongoChatMemoryStore mongoChatMemoryStore;

    @Autowired
    private RestClient restClient;

    @Value("${es.index-name:}")
    private String indexName;

    @Autowired
    private EmbeddingModel embeddingModel;


    @Bean
    ChatMemoryProvider chatMemoryProviderXiaozhi() {
        return memoryId -> MessageWindowChatMemory.builder()
                .id(memoryId)
                .maxMessages(20)
                .chatMemoryStore(mongoChatMemoryStore)
                .build();
    }


    @Bean
    ContentRetriever contentRetrieverXiaozhi() {
        ElasticsearchEmbeddingStore elasticsearchEmbeddingStore = ElasticsearchEmbeddingStore
                .builder()
                .configuration(ElasticsearchConfigurationKnn.builder().numCandidates(1024).build())
                .restClient(restClient)
                .indexName(indexName)
                .build();


        // 创建一个 EmbeddingStoreContentRetriever 对象，用于从嵌入存储中检索内容
        return EmbeddingStoreContentRetriever
                .builder()
                // 设置用于生成嵌入向量的嵌入模型
                .embeddingModel(embeddingModel)
                // 指定要使用的嵌入存储
                .embeddingStore(elasticsearchEmbeddingStore)
                // 设置最大检索结果数量，这里表示最多返回 1 条匹配结果
                .maxResults(1)
                // 设置最小得分阈值，只有得分大于等于 0.4 的结果才会被返回（TODO:0.8的时候好像查不到？）
                .minScore(0.4)
                // 构建最终的 EmbeddingStoreContentRetriever 实例
                .build();
    }

}
